package com.start.common.sql;

import com.start.common.std.StartBaseSingleton;
import com.start.common.std.StartSingletonFactory;
import com.start.common.tools.SpringContextTools;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class StartSQLMappingManage extends StartBaseSingleton<StartSQLMappingManage> {

    private static Map<String, IStartSQLFuncConvert> funcConvertMap = null;

    private static Map<String, IStartSQLFieldConvert> sqlFieldTypeMappingMap = null;


    public static StartSQLMappingManage getInstance() {
        return StartSingletonFactory.get(StartSQLMappingManage.class);
    }

    /**
     * 调用初始化函数
     */
    @Override
    public void init() {
        initFunMap();
        initFieldMap();
    }

    private void initFunMap() {
        funcConvertMap = new HashMap<>();
        Map<String, IStartSQLFuncConvert> beans = SpringContextTools.getBeans(IStartSQLFuncConvert.class, false);
        if (beans == null || beans.isEmpty()) return;
        funcConvertMap = beans.values().stream().filter(e -> StringUtils.isNotBlank(e.getDataBaseType())).collect(Collectors.toMap(IStartDataBaseType::getDataBaseType, (e) -> e, (e1, e2) -> e1));
    }

    private void initFieldMap() {
        sqlFieldTypeMappingMap = new HashMap<>();
        Map<String, IStartSQLFieldConvert> beans = SpringContextTools.getBeans(IStartSQLFieldConvert.class, false);
        if (beans == null || beans.isEmpty()) return;
        sqlFieldTypeMappingMap = beans.values().stream().filter(e -> StringUtils.isNotBlank(e.getDataBaseType())).collect(Collectors.toMap(IStartDataBaseType::getDataBaseType, (e) -> e, (e1, e2) -> e1));
    }

    /**
     * 获取数据库函数映射处理器
     *
     * @param dbType
     * @return
     */
    public IStartSQLFuncConvert getFunConvert(String dbType) {
        return funcConvertMap.getOrDefault(dbType, null);
    }

    /**
     * 获取数据库表字段映射处理器
     *
     * @param dbType
     * @return
     */
    public IStartSQLFieldConvert getFieldConvert(String dbType) {
        return sqlFieldTypeMappingMap.getOrDefault(dbType, null);
    }


}
